define(function(require, exports, module) {

	var $ = require('jquery');
	require('../util/jquery.icheck');
	require('jbox');
	require('../util/tinymce-page.js');
	require('jquery/jquery-validation/1.11.0/jquery.validate');
	require('jquery/jquery-validation/1.11.0/messages_zh');
	require('artTemplate/artTemplate/2.0.1/template.js');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-json/2.4.0/jquery.json.js');
	require('jquery/jquery-cookie/1.3.1/jquery.cookie.js');
	require('jscal2/jscal2/1.9/jscal2.js');
	require('jscal2/jscal2/1.9/lang/cn.js');
	require('seajs/seajs/2.1.1/sea.js');
	require('spin/1.3/spin.js');

	require('jquery/jquery-file-upload/8.8.5/vendor/jquery.ui.widget.js');
	require('jquery/jquery-file-upload/8.8.5/jquery.iframe-transport.js');
	require('jquery/jquery-file-upload/8.8.5/jquery.fileupload.js');
	var List = require('../util/list');
	require('../util/charCount');

	var cg = $("#startPid").val();// 草稿id
	var uid = "";
	var roles = '';
	var projectId = '';
	var n = '';
	var fundTarget='';
	var comp='';
	var pid='';
	if($g_user.login == 'true'){
		uid = ''+$g_user.id;
	}else{
		uid = '-1';
	}
	
	if(uid=="-1"){
		var submit = function (v, h, f) {
		    if (v == 'ok')
		    	window.location.href=$CONFIG.base_url +"/login";
		};
		$.jBox.confirm("登录超时，请点击确定重新登录？", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
	}

	//获取页面地址参数
	exports.getParam = function(path,name) {
		var value = path.substr(path.lastIndexOf('?') + 1);
		var  reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)","i");
		var param = value.match(reg);
		if (param != null) return param[2]; 
		return null;
	};

	var path = decodeURIComponent(window.location.href);
	pid= exports.getParam(path,"pid");
	projectId = pid;
	$("#startPid").val(pid);
	// 获得当前日期
	var today = new Date();
	var y = today.getFullYear(); // 获取完整的年份(4位,1970-????)
	var m = today.getMonth() + 1; // 获取当前月份(0-11,0代表1月)
	var d = today.getDate(); // 获取当前日(1-31)
	var t_today = ''; // 获取当前时间
	if (m < 10) {
		m = 0 + "" + m;
		t_today = parseInt(y + "" + m + "" + d);
	} else {
		t_today = parseInt(y + "" + m + "" + d);
	}

	// 移除遮罩按钮在tabs上
	exports.addButton = function(e) {
		$('#tab-cover').css("margin-left", e + "px");
	};

	//选择项目类别
	$("#kind-select").on("click",".kind-item",function(){
		$(".kind-item").removeClass('active');
		$(this).addClass('active');
		$("#projectCategory").val($(this).attr("value"));
	});
	//选择收益类别
	$("#profit-select").on("click",".fit-item",function(){
		$(".fit-item").removeClass('active');
		$(this).addClass('active');
		$("#profitCategory").val($(this).attr("value"));
	});

	//箭头
	$(".t1").click(function(){
		$(".start-tab").css("background-position","0px -39px");
	});
	// 城市三级联动
	var tasktype = '';
	exports.loadCitytype = function(parent, type, select) {
		$.get($CONFIG.base_url + "/api/region/list/parent", {
			parentId : parent
		}, function(data) {
			var i, len = data.length, html = '';
			for (i = 0; i < len; i++) {
				html += '<option value="' + data[i].id + '">' + data[i].name
						+ '</option>';
			}
			$("#region-" + type + "-select").empty().append(html);
			$("#region-" + type + "-select").val(select);
		});
	};
	// 分配城市联动
	exports.getCityTypeSelect = function(parent, type, callback) {
		$.get($CONFIG.base_url + "/api/region/list/parent", {
			parentId : parent
		}, function(data) {
			var i, len = data.length, html = '';
			for (i = 0; i < len; i++) {
				if (i == "0") {
					html += '<option value="' + data[i].id + '" selected>'
							+ data[i].name + '</option>';
					tasktype = data[i].id;
					if(type=="city"){
						$("#startCity").text(data[i].name);
					}
					$("#region-" + type + "-id").val(data[i].id);
				} else {
					html += '<option value="' + data[i].id + '">'
							+ data[i].name + '</option>';
				}
			}
			$("#region-" + type + "-select").empty().append(html);
			switch (type) {
			case "province":
				exports.getCityTypeSelect(tasktype, "city");
				break;
			case "city":
				exports.getCityTypeSelect(tasktype, "county");
				break;
			default:
				break;
			}
			if (typeof (callback) == "function") {
				callback();
			}
		});
	};
	$("#region-county-select").change(function() {
		$("#region-county-id").val($(this).val());
	});
	$("#region-province-select").change(function() {
		exports.getCityTypeSelect($(this).val(), "city");
		$("#region-province-id").val($(this).val());
	});
	$("#region-city-select").change(function() {
		exports.getCityTypeSelect($(this).val(), "county");
		$("#region-city-id").val($(this).val());
	});
	module.exports = List;
	function List() {
		this.options = [];
	}
	;
	exports.options = {
		listLink : '',
		listParams : '',
		pageLink : '',
		pageParams : ''
	};

	if ($g_user.login == 'true') {
		uid = '' + $g_user.id;
		// 获取用户信息
		exports.options.userlink = $CONFIG.base_url + "/api/user";
		exports.options.userParams = {
			"uid" : uid
		};
		var userInfor = $.get(exports.options.userlink,
				exports.options.userParams);
		userInfor.done(function(data) {
			roles = data.user.roles;
		});
	} else {
		uid = '-1';
	}
	// 加载项目分类
	exports.category = function(e) {
		var categoryList = new List();
		categoryList.options.template = "kind-select-template";
		categoryList.options.container = "#kind-select";
		categoryList.options.links = {
			"list" : $CONFIG.base_url + "/api/category"
		};
		categoryList.load(function() {
			$('.sel-group input,#panel-473514 input').iCheck({
				radioClass : 'iradio_minimal-yellow',
				increaseArea : '-10%', // optional
			});
		});
	};
	exports.category();
	// 加载项目收益分类
	var getting = $.get($CONFIG.base_url + "/api/system/project/categorylist",{"type":3});
	getting.done(function(data) {
		data={"data":data};
		var html = template.render("profit-select-template", data);
		$("#profit-select").empty().append(html);
		$('.fit-group input').iCheck({
			radioClass : 'iradio_minimal-yellow',
			increaseArea : '-10%', // optional
		});
	});
	// 提交表单
	exports.submitForm = function submitForm(e, v, callback) {
		var ed = '';
		if (v == "/api/project/add") {
			ed = tinyMCE.get('activityBackground').getContent();
			backGround=ed.replace('<table','<table border="1px solid" width="100%"');
			$("#activityBackground").val(backGround);
		}
		var json = form2js(e, '.', true);
		var postData = $.toJSON(json);
		$.ajax({
			url : $CONFIG.base_url + v,
			type : "POST",
			data : postData,
			contentType : "application/json",
			success : function(data) {
				if (v == "/api/project/add") {
					projectId = data.id;
					$("#pid").val(projectId);
					$(".t2").click();
				}
				if (typeof (callback) == "function") {
					callback();
				}
			},
			error : function() {
				$.jBox.tip('亲~出问题啦，请再试一次！');
			}
		});
	};
	$(".t2").click(function(){
		$(".start-tab").css("background-position","0px -76px");
		if ($("#schedule1").length == 0) {
			exports.addTable("1");
		} else {
			return;
		}
	});
	// 加载个人成就
	exports.loadSchedulel = function(projectId) {
		var schedulel = new List();
		schedulel.options.template = "showPlan-template";
		schedulel.options.container = "#showPlan";
		schedulel.options.links = {
			"list" : $CONFIG.base_url + "/api/project/schedule/list"
		};
		schedulel.options.params = {
			"pid" : projectId
		};
		schedulel.load(function() {
			exports.checkCount();
			var count = 0;
			$(".show_plan>form").each(function() {
				count = count + 1;
			});
			if (count == "0") {
				exports.addTable("1");
				$("#showPlan .delete:last").remove();
				$("#schd-next").hide();
				$("#savePlan").show();
			}else{
				exports.addOperation();
			}
		});
	};
	// 加载服务
	exports.loadGoods = function(projectId) {
		var goods = new List();
		goods.options.template = "showGoods-template";
		goods.options.container = "#showGoods";
		goods.options.links = {
			"list" : $CONFIG.base_url + "/api/project/product/list"
		};
		goods.options.params = {
			"pid" : projectId
		};
		goods.load(function() {
			var count = 0;
			$("#panel-473513 .show_goods .table").each(function() {
				count = count + 1;
			});
			if (count == "0") {
				exports.addGoodsTable("1");
				$("#showGoods .delete:last").remove();
				$(".add_plan").remove();
				$("#goods-next").hide();
				$("#goodsExcuteSave").show();
			}else{
				exports.addGoodsOperation();
			}
			exports.checkCount();
		});
	};
	// 获取项目详情
	exports.loadProject = function(projectId) {
		exports.options.projectLink = $CONFIG.base_url + "/api/project";
		exports.options.projectParams = {
			"uid" : uid,
			"pid" : projectId
		};
		var commentList = $.get(exports.options.projectLink,
				exports.options.projectParams);
		commentList.done(function(data) {
			$("#name").val(data.project.name);
			$("#projectCategory").val(data.project.projectCategory.id);
			$('.kind-item[value="'+ data.project.projectCategory.id +'"]').addClass('active');
			$("#profitCategory").val(data.project.projectBenefit.id);
			$('.fit-item[value="'+ data.project.projectBenefit.id +'"]').addClass('active');
			$("#address").val(data.project.address);
			$("#description").val(data.project.description);
			$("#activityBackground_ifr").contents().find("#tinymce").html(data.project.activityBackground);
			var img_id = data.project.photoUrl.substr(data.project.photoUrl.lastIndexOf("/")+1);
			$("#coverId").val(img_id);
			$("#coverId-preview").append("<img>")
			$("#coverId-preview img").attr("src", data.project.photoUrl+"/170x100/");
			exports.loadCitytype(0, "province", data.project.provinceRegion.id);
			exports.loadCitytype(data.project.provinceRegion.id, "city",
					data.project.cityRegion.id);
			exports.loadCitytype(data.project.cityRegion.id, "county",
					data.project.districtRegion.id);
			$("#region-county-id").val(data.project.districtRegion.id);
			$("#region-province-id").val(data.project.provinceRegion.id);
			$("#region-city-id").val(data.project.cityRegion.id);
			$("#startCity").text(data.project.cityRegion.name);


			$("#userName").val(data.project.userRealName);
			$("input[name=userGender]").val(data.project.userGender);
			$("#tel").val(data.project.userPhone);
			$("#qq").val(data.project.userQQ);
			if (data.project.projectCategory.id != "") {
				var a = data.project.projectCategory.id-1;
				a="checkb" + a;
				$("#kind-select label").each(function() {
					var check = $(this).attr("class");
					if (a == check) {
						$(this).click();
					}
				});
				
			}
			if (data.project.projectBenefit.id != "") {
				var a = data.project.projectBenefit.id-1;
				a="checkf" + a;
				$("#profit-select label").each(function() {
					var check = $(this).attr("class");
					if (a == check) {
						$(this).click();
					}
				});
				
			}
			if (data.project.institution.user.gender == "1") {
				$("#label-man").click();
			} else {
				$("#label-woman").click();
			}
		});
	};
	
	
	// 上传头像
	exports.fileUpload = function fileUpload(e, v, a, s) {
		$("#" + a).fileupload(
				{
					url : $CONFIG.base_url + e,
					dataType : 'json',
					formData : {
						uid : $g_user.id
					},
				 add: function (e, data) {
				        var goUpload = true;
				        var uploadFile = data.files[0];
				        if (!(/\.(gif|jpg|jpeg|png)$/i).test(uploadFile.name)) {
				        	$.jBox.tip('亲~请选择正确的图片格式');
				            goUpload = false;
				        }
				        if (uploadFile.size > 1048576) { // 1mb
				        	$.jBox.tip('亲~图片太大了，最大不超过1mb哦！');
				            goUpload = false;
				        }
				        if (goUpload == true) {
				            data.submit();
				        }
				    },
				    progressall : function(e, data) {
						var progress = parseInt(data.loaded / data.total * 100,10);
						$("#loading-load").show();
						$("#loading-load").text(progress + '%');
					},
					done : function(e, data) {
						 var result = data.result[0].body ? data.result[0].body.innerHTML : data.result;
						$.each(result, function(index, file) {
							var html = '<img src="' + $CONFIG.base_url
									+ '/common/attachment/download/' + file.id
									+ '/170x100"/>';
							if (s == "file-input") {
								$("#"+v+"-preview").empty().append(html);
								$('#' + v).val(file.id);
								$('.' + v + "-name").text(file.fileName);
								$("#loading-load").hide();
							} else {
								$('#' + s).empty().append(html);
								$('#' + v).val(file.id);
								$("#loading-load").hide();
							}
						});
					}
				});
	};


	// 删除个人成就
	exports.del = function del(e, v, callback) {
		var posting = $.post($CONFIG.base_url + v, {
			id : e
		});
		posting.done(function() {
			if (v == "/api/project/schedule/delete") {
				$.jBox.tip("删除成功！");
				exports.loadSchedulel(projectId);
			} else {
				$.jBox.tip("删除成功！");
				exports.loadGoods(projectId);
			}

			if (typeof (callback) == "function") {
				callback();
			}
		});
	};
	
	// 添加日历
	exports.showCalander = function showCalander(e,min,fn) {
		Calendar.setup({
			weekNumbers : true,
			selectionType : Calendar.SEL_SINGLE,
			inputField : e,
			trigger : e,
			onSelect : function() {				
				this.hide();
				if(typeof(fn)=="function"){
					fn();
				}
			},
			showTime : true,
			dateFormat : "%Y-%m-%d %I:%M:%S",
//			dateFormat : "%Y-%m-%d",
			min:min,
			minuteStep:1
		});
	};
	
	// 新增执行计划
	exports.addTable = function addTable(e) {
		$("#savePlan").val("保存");
		$("#panel-473511 .add_schadule").remove();
		$(".show_plan")
				.append(
						"<form id='schedule"
								+ e
								+ "' class='schedule'><input type='hidden' name='project.id' value='"
								+ projectId
								+ "' class='project_id'/><table class='table'><tr><td><input type='hidden' class='stage' name='stage' value='"
								+ e
								+ "'>成就"
								+ e
								+ "</td></tr><tr><td>时间</td><td><input style='width: 200px;' type='text' readonly id='startTime"
								+ e
								+ "' name='startDate' class='form_datetime start_date '/><span style='margin: 0 10px'>至</span><input readonly type='text' id='endTime"
								+ e
								+ "' name='endDate' style='width: 200px;' class='form_datetime end_date'/></td></tr><tr><td>简介</td><td><textarea name='content'  class='do_plan form-control required'></textarea></td></tr><tr class='do_tr'><td></td><td class='operate'><span class='planEdit' id='"
								+ e
								+ "'>编辑</span><span class='delete' id='' data=''>删除</span></td></tr></table></form>");

		var v1 = "startTime" + e;
		var v2 = "endTime" + e;
		if(e==1){
				exports.showCalander(v1,"1970011",function(){
					exports.showCalander(v2,$("#"+v1).val(),function(){
				});
			});	
		}else{
				exports.showCalander(v1,"1970011",function(){
					exports.showCalander(v2,$("#"+v1).val(),function(){
					});
				});
		};
		$("#showPlan .planEdit:last").remove();
	};
	
	// 新增服务设置
	exports.addGoodsTable = function(e) {
		$(".add_plan").remove();
		$("#showGoods .planEdit").hide();
		$("#panel-473513 .show_goods")
				.append(
						"<form id='goodsSetgoodAdit"
								+ e
								+ "' class='goodsSetgoodAdit'><input type='hidden' name='projectId' value='"
								+ projectId
								+ "' class='project_id'> <input type='hidden' name='code' value='2134'><table class='table'><tr><td>服务名称"
								+ e
								+ "</td><td><input type='text' name='name' id='goodsName"
								+ e
								+ "' class='goods_name required' value='' /></td></tr><tr class=''><td>服务图片</td><td><div class='portrait goodsPic'><span class='change-img'  onclick=\"document.getElementById(\'file_upload"
								+ e
								+ "\').click()\"> 上传</span> <input id='photoId"
								+ e
								+ "' type='hidden' value='' name='photoId' class='pho_id'/><div id='file-preview"
								+ e
								+ "'><img src=''  onclick=\"document.getElementById(\'file_upload" 
								+ e
								+ "\').click()\"></img></div><label for='correctPortrait' class='correctPortrait'> <input data='"
								+ e
								+ "' id='file_upload"
								+ e
								+ "'  type='file' name='photoId' class='correctPortrait upload_f'></input></label></div></td></tr>" +
										"<tr><td>服务介绍</td><td><textarea id='goodsText' name='description' class='required'></textarea></td></tr><tr><td>收费标准</td><td><input type='text' name='price' class='price  required' value=''>元</td></tr>" +
										"<tr class='do_tr'><td></td><td class='operate'><span class='planEdit required' id='goodAdite"
								+ e
								+ "' >编辑</span><span class='delete' id='delId"
								+ e
								+ "'}'>删除</span></td></tr></table></form>");
		$("#showGoods .planEdit:last").remove();
	};

	//服务描述keyup事件
	$("#showGoods").on("keyup","#goodsText",function(){
		var text=$(this).val();
		if(text.length>255){
			$.jBox.tip("服务描述最多255个字");
			$(this).val(text.substring(0,255));
		}
	});
	
	//服务描述blur事件
	$("#showGoods").on("blur","#goodsText",function(){
		var text=$(this).val();
		if(text.length>255){
			$.jBox.tip("服务描述最多255个字");
			$(this).val(text.substring(0,255));
		}
	});
	
	//服务描述粘贴事件
	$("#showGoods").on("paste","#goodsText",function(){
		var text=$(this).val();
		if(text.length>255){
			$.jBox.tip("服务描述最多255个字");
			$(this).val(text.substring(0,255));
		}
	});
	
	// 个人成就操作添加
	exports.addOperation = function addOperation() {
		$("#panel-473511 .add_schadule:last").remove();
		$("#panel-473511 input,#panel-473511 textarea").css("background-color",
				"#f4f4f4").attr("readonly", "readonly");
		$(".stage").removeAttr("readonly").css("background-color", "#ffffff");
		$("#panel-473511 .showaction").append("<span class='add_schadule'>增加新成就</span>");
	};
	// 服务操作添加
	exports.addGoodsOperation = function() {
		$("#panel-473513 .add_plan:last").remove();
		$("#panel-473513 .show_action").after(
				'<span  class="add_plan" style="line-height:55px;">增加新服务</span>');
		$("#panel-473513 input,#panel-473513 textarea").css("background-color",
				"#f4f4f4").attr("readonly", "readonly");
	};
	// 检测最小值
	exports.checkMin = function(obj, length) {

	};

	
	
	
	// 发起服务
	$("#startProjectSubmit").click(function() {

		if(uid=="-1"){
			var submit = function (v, h, f) {
			    if (v == 'ok')
			    	window.location.href=$CONFIG.base_url +"/login";
			};
			$.jBox.confirm("登录超时，请点击确定重新登录？", "<span style='text-align:center;width:100%;display:block;color: #834313;'><span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span></span>", submit);
			return;
		}
		
		if ($("#address").val().length < 6) {
			$.jBox.tip("亲～详细地址最少" + 6 + "字！");
			return;
		};
		var vald='';
		$("#startProjectForm .required").each(function(){
			if($(this).val()==""){
				vald=$(this).attr("id");
			}
		});
		if(vald!=""){
			switch(vald){
			case "name":
				$.jBox.tip("亲~服务名称不能为空哦！");
				$("#"+vald).focus();
				return;
				break;
			
			}
		}
		if ($("#coverId").val() == "") {
			$.jBox.tip("亲～您还没有上传图片哦");
			return;
		}
		bg = tinyMCE.get('activityBackground').getContent();
		if (bg == "") {
			$.jBox.tip("亲～您还没有填写服务详情哦");
			return;
		}
	if(bg.length>15000){
		$.jBox.tip("亲~服务详情建议不要超过1500字，如果您有需求请联系管理员！");
		return;
	}
		
		$.jBox.tip("<span style='text-align:center;width:100%;display:block;color: #834313;'>正在努力提交，请稍后...</span>","loading");
		exports.submitForm("panel-308006", "/api/project/add", function() {
			$.jBox.closeTip();
			$("#startPid").val(projectId);
			fundTarget=$("#fundTarget").val();
			exports.loadYuLan(projectId);
			exports.addButton("153");
		});
	});
	// 保存个人成就
	$("#savePlan").click(function() {
		var id = $(".show_plan form:last").prop("id");
		if($("#" + id+" .start_date").val()==""||$("#" + id+" .end_date").val()==""){
			$.jBox.tip("亲~时间不能为空哦！");
			return;
		}
	    if($("#" + id+" textarea").val()==""){
	    	$.jBox.tip("亲~简介不能为空哦！");
			return;
	    }
	    $.jBox.tip("<span style='text-align:center;width:100%;display:block;color: #834313;'>正在努力提交，请稍后...</span>","loading");
		exports.submitForm(id, "/api/project/schedule/add", function() {
			$.jBox.closeTip();
			exports.loadSchedulel(projectId);
			exports.addOperation();
			$.jBox.tip("保存成功！");
			$("#savePlan").hide();
			$("#schd-next").show();
		});
	});
	$("#schd-next").click(function() {
		$(".t4").click();
	});
	$(".t4").click(function(){
		$(".start-tab").css("background-position","0px -112px");
		exports.loadGoods(projectId);
		if ($("#showGoods").length == 0) {
			exports.addGoodsTable("1");
		} else {
			return;
		}
		
		exports.addButton("231");
	});
	// 新增成就
	$("#panel-473511").on("click", ".add_schadule", function() {
		var no = 1;
		$("#panel-473511 .planEdit").each(function() {
			no++;
		});
		exports.addTable(no);
		$("#panel-473511 .planEdit").hide();
		$(".stages").val(no);
		$("#savePlan").show();
		$("#schd-next").hide();
	});
	// 编辑成就
	$("#panel-473511").on(
			"click",
			".planEdit",
			function() {
				n = $(this).attr("id");
				$("#updatePlan").show();
				$("#schd-next").hide();
				$("#savePlan").hide();
				
				if(n==1){
					exports.showCalander("startTime"+n,"1970011",function(){					
						exports.showCalander("endTime"+n,"1970011",null);
					});
				}else{
					exports.showCalander("startTime"+n,"1970011",function(){					
						exports.showCalander("endTime"+n,"1970011",null);
					});
				};
				$("#panel-473511 .add_schadule").remove();
				$("#schedule" + n + " .form_datetime").css("background-color",
						"#ffffff")
						//.removeAttr("readonly")
						;
				$("#schedule" + n + " .do_plan").css("background-color",
						"#ffffff")
						.removeAttr("readonly")
						;
				$("#updatePlan").click(
						function() {
							if($("#schedule" + n+" .start_date").val()==""||$("#schedule" + n+" .end_date").val()==""){
								$.jBox.tip("亲~时间不能为空哦！");
								return;
							}
							if($("#schedule" + n+" textarea").val()==""){
						    	$.jBox.tip("亲~简介不能为空哦！");
								return;
						    }
							$.jBox.tip("正在更新,请稍后...");
							$('.project_id' + n).val(projectId);
							exports.submitForm("schedule" + n,
									"/api/project/schedule/update", function() {
										exports.addOperation();
										$("#updatePlan").hide();
										$("#schd-next").show();
										$.jBox.tip("更新成功！");
									});
						});
			});
	// 删除计划
	$("#panel-473511").on("click", ".delete", function() {
		var data = $.parseJSON($(this).attr("data"));
		if(data==null){
			$("#showPlan form:last").remove();
			$("#panel-473511 .planEdit").show();
			exports.addOperation();
			$("#savePlan").hide();
			$("#schd-next").show();
		}else{
			var submit = function (v, h, f) {
			    if (v == 'ok')
					exports.del(data.id, "/api/project/schedule/delete");
			    else if (v == 'cancel')
			    return true; //close
			};
			$.jBox.confirm("亲~您确定要删除吗？", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
		}
	});
	// 删除服务
	$("#panel-473513").on("click", ".delete", function() {
		var data = $.parseJSON($(this).attr("data"));
		if(data==null){
			$("#showGoods form:last").remove();
			$("#showGoods .planEdit").show();
			exports.addGoodsOperation();
			$("#goodsExcuteSave").hide();
			$("#goods-next").show();
		}else{
			var submit = function (v, h, f) {
			    if (v == 'ok')
			    	exports.del(data.id, "/api/project/product/del");
			    else if (v == 'cancel')
			    return true; //close
			};
			$.jBox.confirm("亲~您确定要删除吗？", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
		}
	});
	$("#goods-next").click(function() {
		$(".t5").click();
	});

	
	
	$(".t5").click(function(){
		$(".start-tab").css("background-position","0px -184px");
	});
	
	// 判断项目是否包含所有的信息（计划，预算，服务）
	var scheduleLength = '';
	var productLength = '';
	exports.getProject = function(projectId, callback) {
		$.get($CONFIG.base_url + "/api/project/schedule/list", {
			pid : projectId,
		}, function(data) {
			scheduleLength = data.schedule.length;
		});
		$.get($CONFIG.base_url + "/api/project/product/list", {
				pid : projectId,
			},  function(data) {
					productLength = data.result.length;
					if (typeof (callback) == "function") {
						callback();
					}
				});

		
	};
	// 项目完整时更改状态为1
	exports.changeProjectStatus = function(pdata) {
		$.jBox.tip("正在努力提交，请稍后...","loading");
		var postData = $.toJSON(pdata);
		////console.log("asasa"+postData);
		$.ajax({
			url : $CONFIG.base_url + "/api/project/submit",
			type : "POST",
			data : postData,
			// dataType : "json",
			contentType : "application/json",
			success : function(data) {
				time = setInterval(exports.auto_jump,1000);
			},
			error : function() {
				$.jBox.tip('填写有误，请重试！');
			}
		});
	};
	
	
	// 定时器
	var outtimes="6";
	exports.auto_jump = function auto_jump() {
		outtimes--;
		$.jBox.tip('提交成功，我们将在<span style="color:#FF0000;font-weight: bold;font-size:14px;padding:0px 5px;">3个工作日</span>内处理，请耐心等待！<span style="color:#FF0000;font-weight: bold;font-size:14px;padding:0px 5px;">'+outtimes+'</span>秒后自动转跳去主页');
		if (outtimes < 0) {
			return false;
		}
		if (outtimes == 0) {
			clearInterval(time);
			$.jBox.closeTip();
			window.location=$CONFIG.base_url+"/recommend";
		} 
	};
	// 提交审核
	$("#checkF").click(
			function() {
				
				 var regexp=/^((\(\d{3}\))|(\d{3}\-))?(1[358]\d{9})$/;//验证手机  
				 var regexp1=/^(0[0-9]{2,3}\-{0,1})?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;//验证座机
				if($("#userName").val()==""){
					$.jBox.tip("亲～真实姓名不能为空！");
					return;
				}else if($("#tel").val()==""){
					$.jBox.tip("亲～电话号码不能为空");
					return;
				}else if($("#qq").val()==""){
					$.jBox.tip("亲～qq号码不能为空");
					return;
				}else if(isNaN($("#qq").val())){
					$.jBox.tip("亲～qq号码只能是数字！");
					$("#qq").val("");
					return;
				}else if(!((regexp.test($("#tel").val()))||(regexp1.test($("#tel").val())))){
					$.jBox.tip("亲～电话号码格式不正确");
					return;
				}
				exports.getProject(projectId, function() {
					if (productLength != "") {
						exports.submitForm("checkSubmit",
								"/api/project/update", function() {
									var pdata = new Object();
									pdata["id"] = projectId;
									pdata["status"] = "1";
									exports.changeProjectStatus(pdata);
								});
					} else {
						$.jBox.tip('服务信息不完整，已保存为草稿！');
						window.readload();
					}
				});
		});

//加载预览
exports.loadYuLan = function(e) {
		$("#yl").remove();
		$("#checkF")
				.after(
						"<input id='yl' type='button' class='raise-submit' value='预览服务'/>");
		$("#yl").click(
			function(){
				window.open($CONFIG.base_url + "/project/preview?id=" + e + "", "_blank");
			})
		};


	// 检测输入字数
	exports.checkCount = function() {
		$("#name").charCount({
			allowed : 30,
			warning : 5
		});
		$("#address").charCount({
			allowed : 100,
			warning : 10
		});
		$("#description").charCount({
			allowed : 200,
			warning : 10
		});
		$("#activityContent").charCount({
			allowed : 500,
			warning : 50
		});
		$(".goods_notice").charCount({
			allowed : 255,
			warning : 50
		});
		$("#userName").charCount({
			allowed : 20,
			warning : 50
		});
		$("#tel").charCount({
			allowed : 11,
			warning : 50
		});
		$("#qq").charCount({
			allowed : 11,
			warning : 50
		});
		$(".do_plan").charCount({
			allowed : 2000,
			warning : 50
		});
		
	};
	exports.checkCount();

	$("#name").blur(function() {
		$("#startProTItle").text($("#name").val());
	});

	$("#region-city-select").change(function() {
		$("#startCity").text($("#region-city-select option:selected").text());
	});

	$("#file-input").click(function() {
		v = "coverId";
		a = $(this).attr("id");
		s = "file-input";
		exports.fileUpload("/common/attachment/upload/multi", v, a, s);
	});
	$("#showGoods").on("click", ".upload_f", function() {
		var d = $(this).attr("data");
		var v = "photoId" + d;
		var a = $(this).attr("id");
		var b = "file-preview" + d;
		exports.fileUpload("/common/attachment/upload/multi", v, a, b);
	});
	// 保存服务信息
	var gid = '';
	$("#goodsExcuteSave").click(function() {
		gid = $("#panel-473513 .show_goods form:last").attr("id");
		if($("#"+gid+" .goods_name").val()==""){
			$.jBox.tip("亲~服务名称不能为空哦!");
			return;
		}
		var vali='';
		$($("#"+gid+" input")).each(function(){
			if($(this).val()==""){
				vali=$(this).attr("name");
			}
		});
		if($("#"+gid+" .pho_id").val()==""){
			$.jBox.tip("亲~您还没有上传服务图片！");
			return;
		}
		if($("#"+gid+" textarea").val()==""){
			$.jBox.tip("亲~服务介绍不能为空哦!");
			return;
		}

		if(vali!=""&&vali!="photoId"){
			switch(vali){
			case "price":
				$.jBox.tip("亲~服务收费不能为空哦!");
				break;
			default:
				break;
			}
			return;
		}
		
		
		$.jBox.tip("正在努力提交，请稍后...","loading");
		
		exports.submitForm(gid, "/api/project/product/add", function() {
			$.jBox.tip("保存成功！");
			exports.loadGoods(projectId);
			$("#goodsExcuteSave").hide();
			$("#goods-next").show();
		});
		exports.addButton("388");
	});
	// 编辑服务
	$("#showGoods").on(
			"click",
			".planEdit",
			function() {
				var s = $(this).prop("id");
				$("#goodsSet" + s + " input")
						.css("background-color", "#ffffff").removeAttr(
								"readonly");
				$("#goodsSet" + s + " textarea").css("background-color",
						"#ffffff").removeAttr("readonly");
				$("#goods-next").hide();
				$("#goodsExcuteSave").hide();
				$("#updateGoods").show();

				$("#updateGoods").click(
						function() {
							
							if($("#goodsSet" + s+" .goods_name").val()==""){
								$.jBox.tip("亲~服务名称不能为空哦!");
								return;
							}
							var vali='';
							$($("#goodsSet" + s+" input")).each(function(){
								if($(this).val()==""){
									vali=$(this).attr("name");
								}
							});
							if($("#goodsSet" + s+" textarea").val()==""){
								$.jBox.tip("亲~服务介绍不能为空哦!");
								return;
							}
							if($("#goodsSet" + s+" .price").val().charAt(0)=="0"){
								$.jBox.tip("亲～服务收费格式不对！");
								return;
							}
							
						/*	
							if(vali!=""&&vali!="photoId"){
								switch(vali){
								case "price":
									$.jBox.tip("亲~服务价值不能为空哦!");
									break;
								case "ammount":
									$.jBox.tip("亲~服务个数不能为空哦!");
									break;
								default:
									break;
								}
								return;
							}
							*/
							$.jBox.tip("正在保存，请稍后...");
							exports.submitForm("goodsSet" + s,
									"/api/project/product/update", function() {
									$.jBox.tip("保存成功！");
										exports.addGoodsOperation();
										$("#goods-next").show();
										$("#updateGoods").hide();
									});
						});
			});
	// 定时器
	var t = '';
	exports.time = function time() {
		t = t - 1;
		if (t < 0) {
			return false;
		}
		if (t == 0) {
			clearInterval(time);
			$(".letter_send_seccuss").hide();
		}
	};
	// 增加新服务
	$("#panel-473513").on("click", ".add_plan", function() {
		var no = 1;
		$("#panel-473513 .planEdit").each(function() {
			no++;
		});
		exports.addGoodsTable(no);
		$("#goods-next").hide();
		$("#updateGoods").hide();
		$("#goodsExcuteSave").show();
	});

	$("#fundTarget").click(function() {
		exports.number("fundTarget");
	});
	$("#validDays").click(function() {
		exports.number("validDays");
	});
	$("#start-content").on('click', '.price', function() {
		exports.number("price");
	});
	$("#start-content").on('click', '.counts', function() {
		exports.number("counts");
	});
	$(".telephone").click(function() {
		exports.number("telephone");
	});
	$(".userQQ").click(function() {
		exports.number("userQQ");
	});
	$("#budgetShow").on('click', 'input', function() {
		var clas=$(this).attr("class");
		exports.number(clas);
	});
	$(".price").click(function() {
		exports.number("price");
	});

	// 输入数字处理
	exports.number = function number(e) {
		$("." + e).blur(function() {
			$(this).val($(this).val().replace(/\D/g, ''));
		}).bind("paste", function() { // CTR+V事件处理
			$(this).val($(this).val().replace(/\D/g, ''));
		});
	};

	// 这是草稿状态
	exports.getCityTypeSelect(0, "province", function() {
		if (cg != ""&&uid!="-1"&&pid == '') {
			fundTarget=$("#fundTarget").val();
			$("#pid").val(cg);
			projectId=cg;
			$.jBox.tip('亲~您上次有未填写完成的服务，请继续完成.');
			exports.getProject(cg, function() {
				$(".project_id").val(projectId);
				if (scheduleLength != "") {
					exports.addButton("232");
					
					var total = parseInt($('.total_budget :last').text());
					if(total > 0){
						$('#budgetSubmit').show();
					}
				}
				if (productLength != "") {
					exports.addButton("387");
					
				}
				exports.loadYuLan(projectId);
				exports.loadSchedulel(projectId);
				$("#schd-next").show();
				$("#savePlan").hide();
				exports.loadGoods(projectId);
				$("#goods-next").show();
				$("#goodsExcuteSave").hide();
				exports.loadProject(projectId);
			});
		} else if(pid != ''&&uid!="-1") {
			$("#pid").val(pid);
			projectId=pid;
			exports.getProject(pid, function() {
				$(".project_id").val(projectId);
				if (scheduleLength != "") {
					exports.addButton("232");
					
					var total = parseInt($('.total_budget :last').text());
					if(total > 0){
						$('#budgetSubmit').show();
					}
				}
				if (productLength != "") {
					exports.addButton("387");
					
				}
				exports.loadYuLan(projectId);
				exports.loadSchedulel(projectId);
				$("#schd-next").show();
				$("#savePlan").hide();
				exports.loadGoods(projectId);
				$("#goods-next").show();
				$("#goodsExcuteSave").hide();
				exports.loadProject(projectId);
			});
		}

	});
	

});
